package cn.xspace.wnx.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.xspace.android.xafcommon.base.BaseMapActivity;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.IntentConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.xspace.wnx.R;

/**
 * Wubj 创建于 2017/4/6.
 */
public class MapLocationGetActivity extends BaseMapActivity implements AMap.OnMapScreenShotListener,
        AMapLocationListener {

    private static final String TAG = MapLocationGetActivity.class.getSimpleName();

    protected OnLocationChangedListener mListener;

    private String address = "";
    private double latitude = 0.0;
    private double longitude = 0.0;
    private boolean isShowMap;

    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    private String localPath;
    private AMapLocation lastLocation;

    @Override
    protected void getIntentData() {
        isShowMap = getIntent().getBooleanExtra(IntentConstant.IS_SHOW_MAP, false);
        if (isShowMap) { //是否是仅展示地图
            latitude = getIntent().getDoubleExtra(IntentConstant.LATITUDE, 0);
            longitude = getIntent().getDoubleExtra(IntentConstant.LONGITUDE, 0);
            address = getIntent().getStringExtra(IntentConstant.ADDRESS);
        }
    }

    @Override
    protected void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setupLocationStyle();
    }

    protected void setupLocationStyle() {
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }

    @Override
    protected void initTitleBar() {
        if (isShowMap) {
            mTitleBar.setRightLayoutVisibility(View.GONE);
            mTitleBar.setTitle(address);
        }
    }

    protected void initEventNew() {
        super.initEventNew();
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shotScope();
            }
        });
    }

    /**
     * 截图的方法
     */
    private void shotScope() {
        aMap.getMapScreenShot(this);
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                lastLocation = amapLocation;
                mLocationErrText.setVisibility(View.GONE);
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                mTitleBar.setTitle(amapLocation.getAddress());
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                mLocationErrText.setVisibility(View.VISIBLE);
                mLocationErrText.setText(errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        if (isShowMap) {//仅仅是展示地图
            LogUtil.d(TAG, "wubaojie>>>activate: 展示地图");
            addMarker();
        } else {
            LogUtil.d(TAG, "wubaojie>>>activate: 激活定位");
            mListener = listener;
            if (mLocationClient == null) {
                mLocationClient = new AMapLocationClient(this);
                AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
                //设置定位监听
                mLocationClient.setLocationListener(this);
                //设置为高精度定位模式
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                //设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
                // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
                // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
                // 在定位结束后，在合适的生命周期调用onDestroy()方法
                // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
                mLocationClient.startLocation();
            }
        }
    }

    private void addMarker() {
        aMap.clear();
        LatLng latLng = new LatLng(latitude, longitude);
        aMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                .position(latLng)
                .draggable(true));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        super.deactivate();
        LogUtil.d(TAG, "wubaojie>>>deactivate: 停止定位");
        mListener = null;
    }

    @Override
    public void onMapScreenShot(Bitmap snapshot) {
        localPath = AppConstant.IMAGE_ADDRESS + System.currentTimeMillis() + AppConstant.SUFFIX_PNG;
        File localFile = new File(localPath);
        FileOutputStream out;
        try {
            out = new FileOutputStream(localFile);
            if (snapshot.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
                out.close();
            }
            T.showSingleL("屏幕截图成功，图片存在: " + localFile.toString());
            sendLocation();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendLocation() {
        Intent intent = this.getIntent();
        intent.putExtra(IntentConstant.LATITUDE, lastLocation.getLatitude());
        intent.putExtra(IntentConstant.LONGITUDE, lastLocation.getLongitude());
        intent.putExtra(IntentConstant.ADDRESS, lastLocation.getAddress());
        intent.putExtra(IntentConstant.SNAP_PATH, localPath);
        this.setResult(RESULT_OK, intent);
        finish();
    }
}
